<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="医师" prop="doctorId">
            <el-select 
              v-model="formData.doctorId" 
              placeholder="请选择父用户"
              clearable
              :disabled="isEditMode"
             >
              <el-option
                v-for="doctor in doctorList"
                :key="doctor.id"
                :label="doctor.nickname"
                :value="doctor.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="日期" prop="date">
            <el-date-picker
              v-model="formData.date"
              type="date"
              :placeholder="formData.date? safeDateFormatter(formData.date) : '请选择日期'"
              class="!w-120px"
              clearable
              :disabled="isEditMode"
              :disabled-date="disabledDateFn"
              value-format="YYYY-MM-DD"
          />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>  

        <el-col :span="12">
          <el-form-item label="上午开始" prop="morningStart">
            <el-time-select
            v-model="formData.morningStart"
            placeholder="开始时间"
            class="!w-120px"
            start="09:00"
            step="00:30"
            end="12:00"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="下午开始" prop="afternoonStart">
            <el-time-select
            v-model="formData.afternoonStart"
            placeholder="开始时间"
            class="!w-120px"
            start="14:00"
            step="00:30"
            end="18:00"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>  
        <el-col :span="12">
          <el-form-item label="上午结束" prop="morningEnd">
            <el-time-select
            v-model="formData.morningEnd"
            placeholder="结束时间"
            class="!w-120px"
            :start=" formData.morningStart"
            step="00:30"
            end="12:00"
            />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="下午结束" prop="afternoonEnd">
            <el-time-select
            v-model="formData.afternoonEnd"
            placeholder="结束时间"
            class="!w-120px"
            :start=" formData.afternoonStart "
            step="00:30"
            end="18:00"
            />
          </el-form-item>
        </el-col>

      </el-row>

      <el-row>

        <el-col :span="12">
          <el-form-item label="上午就诊数" prop="morningCapacity">
            <el-input v-model="formData.morningCapacity" placeholder="请输入就诊人数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="下午就诊数" prop="afternoonCapacity">
            <el-input v-model="formData.afternoonCapacity" placeholder="请输入就诊人数" />
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>

import * as DoctorApi from '@/api/medical/doctor'
import { CommonStatusEnum } from '@/utils/constants'
import * as ScheduleApi from '@/api/medical/schedule'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { FormRules } from 'element-plus'
import dayjs from 'dayjs'
import { reactive } from 'vue'
import { safeDateFormatter } from '@/utils/formatTime'

defineOptions({ name: 'MedicalScheduleForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const doctorList = ref([])// 用户列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  nickname: '',
  doctorId: '',
  date: '' as string | Date, // 明确类型
  morningStart: '',
  morningEnd: '',
  morningCapacity: undefined,
  afternoonStart: '',
  afternoonEnd: '',
  afternoonCapacity: undefined,
  status: CommonStatusEnum.ENABLE,
})
const formRules = reactive<FormRules>({
  date: [{required: true, message: '请选择日期'}]
})
const formRef = ref() // 表单 Ref
const isEditMode = ref(false)



/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type

  if (formType.value === 'create') {
      isEditMode.value = false
    } else {
      isEditMode.value = true
    }

  getDoctorList()

  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const response = await ScheduleApi.getSchedule(id)
      // 确保日期格式正确
      formData.value = {
      ...response,
      date: response.date ? new Date(response.date) : ''
    }
    } finally {
      formLoading.value = false
    }
  }


}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ScheduleApi.ScheduleVO
    if (formType.value === 'create') {
      await ScheduleApi.createSchedule(data)
      message.success(t('common.createSuccess'))
    } else {
      await ScheduleApi.updateSchedule(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    nickname: '',
    doctorId: '',
    date: '',
    morningStart: '',
    morningEnd: '',
    morningCapacity: undefined,
    afternoonStart: '',
    afternoonEnd: '',
    afternoonCapacity: undefined,
    status: CommonStatusEnum.ENABLE,
  }
  formRef.value?.resetFields()
}


/**获取医师列表 */
const getDoctorList = async () => {
  try {
    const response = await DoctorApi.getDoctorList()
    console.log('response:', response)
    doctorList.value = response
    console.log('获取的父用户列表：', doctorList.value)
  } catch (error) {
    console.error('获取父用户列表失败:', error)
    message.error('获取父用户列表失败')
  }
}

const disabledDateFn = (time: unknown) => {
  // 1. 编辑模式下完全不禁用任何日期
  if (isEditMode.value) return false;

  // 2. 安全获取日期对象（兼容所有情况）
  let date: Date;
  try {
    // 处理undefined/null
    if (!time) return false;
    
    // 处理Date对象
    if (time instanceof Date) {
      date = time;
    }
    // 处理Day.js对象（Element Plus内部可能使用）
    else if (typeof time === 'object' && 'toDate' in time) {
      date = (time as { toDate: () => Date }).toDate();
    }
    // 处理时间戳
    else if (typeof time === 'number') {
      date = new Date(time);
    }
    // 其他情况尝试用dayjs解析
    else {
      date = dayjs(time as any).toDate();
    }
  } catch (e) {
    console.warn('日期解析失败:', e);
    return false;
  }

  // 3. 验证日期有效性
  if (isNaN(date.getTime())) return false;

  // 4. 比较日期（禁用今天之前的日期）
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return date < today;
};

</script>
